package com.fsp.streamAPITest01;

import org.assertj.core.util.VisibleForTesting;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fushengping
 * @className StreamTest
 * @description
 * @date 2021/12/3 16:56
 */
public class StreamTest {
    private static List<Person> list;
    static {
        list = new ArrayList<>();
        list.add(new Person("i", 18, "杭州", 999.9));
        list.add(new Person("am", 19, "温州", 777.7));
        list.add(new Person("iron", 21, "杭州", 888.8));
        list.add(new Person("iron", 17, "宁波", 888.8));
    }

    public static void main(String[] args) {
        /*1.获取所有的Person的名字*/
        List<String> collect = list.stream().map(Person::getName).collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("\n--------------------------------\n");
        /*2.获取一个List，每个元素的内容为：{name}来自{address}(这里没有现成可引用的方法，无法使用方法引用)*/
        List<String> collect1 = list.stream().map(person -> person.getName() + "来自" + person.getAddress()).collect(Collectors.toList());
        System.out.println(collect1);
        System.out.println("\n--------------------------------\n");
        /*3.过滤出年龄大于等于18的Person*/
        List<Person> collect2 = list.stream().filter(person -> person.getAge() >= 18).collect(Collectors.toList());
        System.out.println(collect2);
        System.out.println("\n--------------------------------\n");
        /*4.1过滤出年龄大于等于18 并且 月薪大于等于888.8 并且 来自杭州的Person(该方法较粗糙)*/
        List<Person> personStream = list.stream().filter(person -> (person.getAge() >= 18 && person.getSalary() >= 888.8 && person.getAddress().equals("杭州"))).collect(Collectors.toList());
        System.out.println(personStream);
    }
    /*4.2 较好的写法：当我们需要给filter()、map()等函数式接口传递Lambda参数时，逻辑如果很复杂，最好抽取成方法，再使用方法引用优先保证可读性*/
    @Test
    public void test4() {
        /*调用isRichAdultInHangZhou方法*/
        List<Person> collect = list.stream().filter(this::isRichAdultInHangZhou).collect(Collectors.toList());
        System.out.println(collect);
    }
    /**
     * 是否杭州有钱人
     *
     * @param person
     * @return
     */
    public boolean isRichAdultInHangZhou(Person person) {
        return person.getAge() >= 18
                && person.getAddress().equals("杭州")
                && person.getSalary() >= 888.8;
    }

}
